package com.leetcode.partition2;

import com.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author `RKC`
 * @date 2021/8/16 8:42
 */
public class LC144二叉树的前序遍历 {

    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> answer = new ArrayList<>();
        iteration(root, answer);
        return answer;
    }

    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(1, new TreeNode(2), new TreeNode(3));
        n1.left.left = new TreeNode(4);
        n1.left.right = new TreeNode(5);
        n1.right.left = new TreeNode(6);
        System.out.println(preorderTraversal(n1));
    }

    private static void iteration(TreeNode root, List<Integer> answer) {
        if (root == null) return;
        Stack<TreeNode> s = new Stack<>();
        s.push(root);
        while (!s.isEmpty()) {
            TreeNode cur = s.pop();
            answer.add(cur.val);
            if (cur.right != null) s.push(cur.right);
            if (cur.left != null) s.push(cur.left);
        }
    }

    private static void recursion(TreeNode root, List<Integer> answer) {
        if (root == null) return;
        answer.add(root.val);
        recursion(root.left, answer);
        recursion(root.right, answer);
    }
}